#include <d_bluetooth/bluetooth.h>
/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-04-04     donghaomin       the first version
 */

#include <string.h>
d_bule_revcmd d_revbuffer;
unsigned char locat_data[20];
UART_HandleTypeDef huart2;



// 蓝牙指令通用接口，搭配#define的AT指令使用即可
errornum bluetooth_AT_COM_CMD(void *cmd_ack,void *cmd_ans) {
    errornum ret = DIAG_OK;
    unsigned int overtime = 0;
    while(!(USART_RX_STA&0x8000)) {
        HAL_UART_Transmit_IT(&huart2,(uint8_t *)cmd_ack,strlen(cmd_ack));
        rt_thread_mdelay(500);
        overtime++;
        if(overtime > OVERTIME_TIMES) {
            ret = DIAG_OVERTIM_ERR;
            rt_kprintf("AT CMD time out\n");
            return ret;
        }
    }
    int len=USART_RX_STA&0x3fff;
    memcpy(locat_data,USART_RX_BUF,len);
    rt_kprintf("strlen(cmd_ans) %d\n",strlen(cmd_ans));
    int dong = memcmp(locat_data,cmd_ans,strlen(cmd_ans));
    if(dong!=0){
        rt_kprintf("AT False!%s\n",cmd_ack);
        ret = DIAG_BLUE_ERR;
    }
    else {
        rt_kprintf("AT OK!%s\n",cmd_ans);
        ret = DIAG_OK;
    }
    USART_RX_STA=0;
    return ret;
}

// 蓝牙状态运行检测
errornum bluetooth_AT_OK(void) {
    errornum ret = DIAG_OK;
    unsigned int overtime = 0;
    while(!(USART_RX_STA&0x8000)) {
        HAL_UART_Transmit_IT(&huart2,(uint8_t *)AT_OK_ACK,strlen(AT_OK_ACK));
        rt_thread_mdelay(500);
        overtime++;
        if(overtime > OVERTIME_TIMES) {
            ret = DIAG_OVERTIM_ERR;
            rt_kprintf("AT_OK time out\n");
            return ret;
        }
    }
    int len=USART_RX_STA&0x3fff;
    memcpy(locat_data,USART_RX_BUF,len);
    int dong = memcmp(locat_data,AT_OK_ANS,strlen(AT_OK_ANS));
    if(dong!=0){
        rt_kprintf("AT False\n");
        ret = DIAG_BLUE_ERR;
    }
    else {
        rt_kprintf("AT OK\n");
        ret = DIAG_OK;
    }
    USART_RX_STA=0;
    return ret;
}
// 蓝牙从机初始化，主要执行一些AT指令，包含设置波特率等信息
errornum bluetooth_Init(void) {
    errornum ret = DIAG_OK;
    return ret;
}
// 蓝牙与从机连接的信息，也就是连接的状态
errornum bluetooth_Connect(void) {
    errornum ret = DIAG_OK;
    return ret;
}

